import { useEffect, useMemo } from 'react'
import productDetail from "../const/product-detail.json";
// import computedTotal from "./computedTotal";

const useList = (state,dispatch) => {
  // 存放列表状态

  // 获取选择的列表 详细列表
  const {list, detailList} = state
  // 设置列表数据
  useEffect(()=>{
    const detailListItem=list.filter(item=>{
      return detailList.every(it=>{
        return it.img!==item
      })
    })
    const detailListAdd=detailListItem.map(item=>{
      let pItem=productDetail[item]
      pItem.count = 1
      return pItem
    })
    const detailListNew=detailList.filter(item=>{
      return list.some(it=>{
        return item.img===it
      })
    })
    
    dispatch({
      type:'detailList',
      detailList: [...detailListNew,...detailListAdd]
    })
  },[list])
  // 计算总价总数
  useEffect(()=>{
    const totalCount=detailList.reduce((total,next)=>{
      return total + next.count
    },0)
    const totalPrice=detailList.reduce((total,next)=>{
      return total + (next.count * ~~next.price)
    }, 0)
    const allChecked=detailList.every(item=>{
      return item.checked
    })&&detailList.length>0
    dispatch({
      type: 'totalCount',
      totalCount
    })
    dispatch({
      type: 'totalPrice',
      totalPrice
    })
    dispatch({
      type: 'allChecked',
      allChecked
    })
  }, [detailList])

  const checkedProduct= useMemo(()=>{
    
    return detailList.reduce((total,next)=>{
      if(next.checked){
        return {
          checkedCount:total.checkedCount + next.count,
          checkedPrice:total.checkedPrice + (next.count * ~~next.price)
        }
      }else{
        return total
      }
    }, {checkedCount:0,checkedPrice:0})
  },[detailList])

  return checkedProduct
}

export default useList
